package com.strive.village.security;

import cn.hutool.json.JSONUtil;
import com.strive.village.common.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: strivePeng
 * @CreateTime: 2024年04月19日
 * @Description: 权限不足处理器
 **/

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8"); // 设置编码
        // 权限不足 设置一个权限不足状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 权限不足状态码
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        // 返回一个异常信息
        Result result = Result.fail(e.getMessage());
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
